/**
 * Description:
 * User: Vijay <1937832819@qq.com>
 * Date: 2020/08/19
 * Time: 10:20
 */

package models

import "github.com/astaxie/beego/orm"

type Admin struct {
	Id        int
	Account   string
	Username  string
	Password  string
	RoleNames string
	Tel       string
	Email     string
	Sex       int
	Status    int
	CreatedAt string
	UpdatedAt string
	DeletedAt string
}

func (a *Admin) TableName() string {
	return TableName("admins")
}

func AdminAdd(a *Admin) (int64, error) {
	return orm.NewOrm().Insert(a)
}

func AdminGetByName(account string) (*Admin, error) {
	a := new(Admin)
	err := orm.NewOrm().QueryTable(a.TableName()).Filter("account", account).One(a)
	if err != nil {
		return nil, err
	}
	return a, nil
}

func AdminGetList(page, pageSize int, filters ...interface{}) ([]*Admin, int64) {
	offset := (page - 1) * pageSize
	list := make([]*Admin, 0)
	a := new(Admin)
	query := orm.NewOrm().QueryTable(a.TableName())
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			query = query.Filter(filters[k].(string), filters[k+1])
		}
	}
	total, _ := query.Count()
	query.OrderBy("-id").Limit(pageSize, offset).All(&list)
	return list, total
}

func AdminGetById(id int) (*Admin, error) {
	a := new(Admin)
	err := orm.NewOrm().QueryTable(a.TableName()).Filter("id", id).One(a)
	if err != nil {
		return nil, err
	}
	return a, nil
}

func (a *Admin) Update(fields ...string) error {
	if _, err := orm.NewOrm().Update(a, fields...); err != nil {
		return err
	}
	return nil
}
